/*
 * @lc app=leetcode.cn id=289 lang=typescript
 *
 * [289] 生命游戏
 */

// @lc code=start
/**
 Do not return anything, modify board in-place instead.
 */
function gameOfLife(board: number[][]): void {
  const n = board.length;
  const m = board[0].length;
  const directions = [
    [-1, -1],
    [-1, 0],
    [-1, 1],
    [0, -1],
    [0, 1],
    [1, -1],
    [1, 0],
    [1, 1],
  ];
  const cnt = new Array(n).fill(0).map(() => new Array(m).fill(0));

  // 计算每个点周围的活细胞数
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < m; j++) {
      let count = 0;
      for (const [x, y] of directions) {
        const newX = i + x;
        const newY = j + y;
        if (newX < 0 || newX >= n) continue;
        if (newY < 0 || newY >= m) continue;
        if (board[newX][newY] !== 0) count++;
      }
      cnt[i][j] = count;
    }
  }
  // 根据活细胞数重新设置细胞状态
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < m; j++) {
      if (board[i][j]) {
        board[i][j] = cnt[i][j] < 2 || cnt[i][j] > 3 ? 0 : 1;
      } else {
        board[i][j] = cnt[i][j] === 3 ? 1 : 0;
      }
    }
  }
}
// @lc code=end
